package com.cloud.bc.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.bc.mapper.BcWechausersMapper;
import com.cloud.bc.model.entity.BcWechausers;
import com.cloud.bc.model.enums.RedisKey;
import com.cloud.bc.service.BcWechausersService;
import com.cloud.redis.config.RedisUtils;
import com.cloud.wx.model.response.AccessTokenResponse;
import com.cloud.wx.model.response.SnsapiUserinfoResponse;
import com.cloud.wx.util.TokenService;
import com.cloud.wx.util.WxUserinfoService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 微信（用户）
 *
 * @author douhaichao code generator
 * @date 2021-01-19 21:19:33
 */
@Service
@AllArgsConstructor
public class BcWechausersServiceImpl extends ServiceImpl<BcWechausersMapper, BcWechausers> implements BcWechausersService {
    private final RedisUtils redisUtils;
    private final TokenService tokenService;
    private final WxUserinfoService wxUserinfoService;


    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */
    @Override
    public BcWechausers selectOne(BcWechausers req) {
        QueryWrapper queryWrapper = new QueryWrapper<BcWechausers>();
        queryWrapper.setEntity(req);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 根据条件查询所有
     */
    @Override
    public List<BcWechausers> selectAll(BcWechausers req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据对象查询所有分页数据(精确查询)     *      * @return
     */
    @Override
    public IPage<BcWechausers> selectPage(Page page, BcWechausers req) {
        IPage<BcWechausers> list = baseMapper.selectPage(
                page,
                new QueryWrapper<BcWechausers>().setEntity(req));
        return list;
    }

    /**
     * 根据条件统计数据量     *      * @return
     */
    @Override
    public int count(BcWechausers req) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(req);
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public Integer getOpenid(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        String openid = "";
        Integer id = 0;
        SnsapiUserinfoResponse userinfo = null;
        String[] codes = parameterMap.get("code");
        //        1 第一步：用户同意授权，获取code
        String code = codes[0];
//这里是因为我用花生壳做测试，因为域名不受信任，所以回调两次，正式域名redis这里可以去掉
        String key = RedisKey.bcWxCodeRedisKey + code;
        Object o = redisUtils.get(key);
        id = Convert.toInt(o, 0);
        if (id > 0) {
            return id;
        }
//        2 第二步：通过code换取网页授权access_token
        AccessTokenResponse accessToken = tokenService.getAccessToken(code);
//        3 第三步：刷新access_token（如果需要）
//        4 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        userinfo = wxUserinfoService.getUserinfo(accessToken);
//        5 附：检验授权凭证（access_token）是否有效
//        String token = tokenService.getToken();
        openid = userinfo.getOpenid();

        //1.判断bc_wechat_users是否存在，不存在创建
        List<BcWechausers> bcWechausersList = this.selectAll(new BcWechausers().setOpenid(openid));
//        int count = bcWechausersService.count();

        if (null != bcWechausersList || bcWechausersList.size() > 0) {
            BcWechausers bcWechausers = bcWechausersList.stream().findFirst().orElse(new BcWechausers());
            id = bcWechausers.getId();
        }
        if (Convert.toInt(id, 0) <= 0) {
            //如果openid不存在就创建
            BcWechausers bcWechausers = new BcWechausers();
            bcWechausers.setSubscribe(StrUtil.isEmpty(userinfo.getUnionid()) ? 0 : 1);
            bcWechausers.setOpenid(userinfo.getOpenid());
            bcWechausers.setNickname(userinfo.getNickname());
            bcWechausers.setSex(userinfo.getSex());
            bcWechausers.setCity(userinfo.getCity());
            bcWechausers.setCountry(userinfo.getCountry());
            bcWechausers.setProvince(userinfo.getProvince());
            bcWechausers.setLanguage("Cn");
            bcWechausers.setHeadimgurl(userinfo.getHeadimgurl());
            bcWechausers.setSubscribeTime(new Date());
            bcWechausers.setUnionid(userinfo.getUnionid());
            this.save(bcWechausers);
            id = bcWechausers.getId();
        }
        redisUtils.set(key, id, 1, TimeUnit.MINUTES);
        return id;
    }
}
